package com.cn.xt.service.impl;

import com.cn.xt.entity.SysMenu;
import com.cn.xt.entity.SysUser;
import com.cn.xt.enums.XtServerEnum;
import com.cn.xt.fegin.SysFeignService;
import com.cn.xt.service.CustomUserService;
import com.cn.xt.utils.CollectionUtil;
import com.cn.xt.vo.bean.CustomUserBean;
import com.cn.xt.vo.bean.ResourcesBean;
import com.cn.xt.vo.bean.UserBean;
import com.cn.xt.vo.bean.menu.MenuBean;
import com.cn.xt.vo.rsp.fegin.ResponseRsp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户权限业务类
 * @author liuyu on 2021/1/14.
 */
@Service
public class CustomUserServiceImpl implements CustomUserService {

    @Autowired
    private SysFeignService sysFeignService;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //制作用户
        SysUser user = sysFeignService.getUserByUserName(userName);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if(user.getIsDelete()==1){
            throw new UsernameNotFoundException("用户已经删除");
        }
        if(user.getStatus()==0){
            throw new UsernameNotFoundException("用户已经冻结");
        }
        UserBean userBean = new UserBean();
        userBean.setUser(user);
        //获取权限信息
        ResponseRsp result= sysFeignService.getResourcesList(XtServerEnum.SIX.getServerId(),user.getId());
        //设置用户权限树
        List<MenuBean> recursionList= result.getChildList();
        userBean.setMenuList(recursionList);
        //设置用户api接口url集合
        List<String> apiUrlList = new ArrayList<>();
        List<SysMenu> allList = result.getAllList();
        if (!CollectionUtil.isEmpty(allList)) {
            for (SysMenu obj : allList) {
                if (2 == obj.getType()) {
                    apiUrlList.add(obj.getUrl());
                }
            }
        }
        userBean.setApiUrlList(apiUrlList);

        CustomUserBean customUserBean = new CustomUserBean(userBean, true, true, true, true, null);
        return customUserBean;
    }
}
